// 公共方法，定义在mccmsa命名空间下
window.mccmsa = {
    ajax: function(options) {
        var defaultOptions = {
            url: "",
            method: "POST",
            data: {},
            dataType: "json"
        };
 
        var options = $.extend(defaultOptions, options);

        var loadingLayerIndex;
        return $.ajax({
            // TODO url需按实际情况修改路径
            url: "/notvsys" + options.url,
            method: options.method,
            data: options.data,
            dataType: options.dataType,
            beforeSend: function(){
                loadingLayerIndex = layer.load({
                    shade: [0.8, '#393D49']
                });
                if(options.beforeSend && $.isFunction(options.beforeSend)){
                    options.beforeSend();
                }
            },
            success: function(data, xhr){
                if(data.status == 200 || data.status == 300){
                    if(options.success && $.isFunction(options.success)){
                        options.success(data);
                    }
                }else {
					layer.msg(data.message,{time:1000});
                    // 业务错误处理...
                        if(options.errorStatus)options.errorStatus(data);
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                layer.msg('服务器出错，请稍后再试',{time:1000});
                // 服务器错误处理...
            },
            complete: function() {
                layer.close(loadingLayerIndex);
                if(options.complete && $.isFunction(options.complete)){
                    options.complete();
                }
            }
        });
    },

    /*
     * 编译服务器端请求的模板并生成Html
     *
     * opt: {
     *   templateName: 模板文件名
     *   container: 模板容器
     *   callback: 模板添加成功后回调
     * }
     * */
    getHtmlFromRemoteTemplate: function(opt){
        var templatePath = "templates/";

        $.ajax({
            url: templatePath + opt.templateName + ".hbs",
            method: "GET",
            success: function(tmpl){
                var template = Handlebars.compile(tmpl);
                opt.container && opt.container.html(template(opt.data || {}));

                if(opt.callback && $.isFunction(opt.callback)){
                    opt.callback();
                }
            },
            error: function(jqXHR, textStatus, errorThrown){

                // TODO 请求错误处理...通过错误是因为没有找到对应的页面，跳到欢迎页？
            }
        });
    },

    /*
     * 编译页面上的模板并生成Html
     *
     * opt: {
     *   templateId: 模板Id
     *   container: 模板容器
     *   isAppend: 是否将生成的html append到容器，默认为否，直接替换容器内容
     *   callback: 模板添加成功后回调
     * }
     * */
    getHtmlFromLocalTemplate: function(opt){
        if(opt.templateId && $("#" + opt.templateId).length > 0){

            var template = Handlebars.compile($("#" + opt.templateId).html());
            if(opt.isAppend){
                opt.container && opt.container.append(template(opt.data));
            }else{
                opt.container && opt.container.html(template(opt.data));
            }

            if(opt.callback && $.isFunction(opt.callback)){
                opt.callback();
            }
        }
    },

    /*
    * “跳转”，页面内容更新
    * */
    hashChange: function(){
        if ($('#mainContainer'))$('#mainContainer').off();
        // 刷新页面时，如果有模块、步骤信息，显示该模块
        var module = $.bbq.getState( 'module' );
        var step = $.bbq.getState( 'step' );
        if(module && step){
            // 页面内容“跳转”
            mccmsa.getHtmlFromRemoteTemplate({
                templateName: step,
                container: $('#mainContainer'),
                callback: function(){
                    if($.bbq.getState( 'tab' )){
                        var tab = $.bbq.getState( 'tab' );
                        if ($('#tabBar')) {
                            $('#tabBar span').removeClass('current');
                            $('#'+tab).addClass('current');
                            eval(tab+"()");
                        }
                    }
                }
            });

            // 左侧导航选中模块
            $('.current', '#Huifold')    // 之前被选中的模块a元素
                .removeClass('current')  // 去掉被选中样式
                .parent().parent('.info').hide()  // 隐藏所在二级菜单
                .siblings('.selected').removeClass('selected');  // 一级菜单去掉选中样式

            // 新选中的模块a元素
            var moduleNavEle = $('[href="' + module + '"]', '#Huifold');

            // 后添
            $('.arrow-r').remove();
            $('li', '.info').removeClass('current');
            moduleNavEle
                .parent().addClass('current').append('<i class="arrow-r"></i>')  // 加选中样式(->)
                .parent().parent().show()  // 显示二级菜单
                .siblings('h4').addClass('selected');  // 选中一级菜单
        }else{
            mccmsa.goTo()
        }

        // 清除聊天室interval
        clearInterval(window.chatroomIntervalId);
        window.chatroomIntervalId = null;
    },

    /*
    * 调用bbq插件修改url触发页面内容跳转
    *
    * step：步骤名
    * module：模块名
    * params：跳转需要带上的参数
    * */
    goTo: function(step, module, params) { 
        var defaultParams = {
                module: module || 'indexCotent',
                step: step || 'indexCotent'
            };      
        $.bbq.pushState(
            $.extend(defaultParams, params),
            2
        );
    },

    /*
    *作用:三级菜单返回二级菜单
    */
    goBack: function() {
        if ($('#mainContainer'))$('#mainContainer').off();
        window.history.back();
    },
    goModule: function() {
        if ($('#mainContainer'))$('#mainContainer').off();
        var module = $.bbq.getState('module');
        mccmsa.goTo( module, module);
    },
    /*
     *三级菜单跳转方法
     *注:
     *三级导航id为tabBar
     *span元素id名和方法名相同
     */
    tabBar: function(){
        var oldState = $.bbq.getState();
        $("#tabBar").off().on('click','span',function(){
                var tab = {
                    tab : $(this).attr('id')
                };
                $.bbq.pushState(
                    $.extend(oldState, tab),
                    2
                );
        })
    },
    /*
     * ajax分页
     * json:异步获取到的数据
     * pageCount：数据分页总数
     * pageNo：当前获取数据所在页数
     * fn:页面所在步骤方法，方法理应实现根据传入页码获取数据,并展示数据;
     * eleId 分页容器id 默认为layPage，适用于同一页面多个分页
     */
    pageHtml: function(json, fn, eleId){
        eleId = eleId || 'layPage';
        var data = '';
        if(json.result.pageCount && json.result.pageCount != 1 && json.result.pageCount != 0){
            if(json.result.pageCount<=6){
                for(var i=1;i<json.result.pageCount+1;i++){
                    data+='<a class="pageClick" pageNo='+i+'>'+i+'</a>';
                }
            }else if(json.result.pageNo>json.result.pageCount-3){
                data+='<a class="pageClick" pageNo="1">1</a>... ...';
                for(var i=json.result.pageCount-3;i<=json.result.pageCount;i++){
                    data+='<a class="pageClick" pageNo='+i+'>'+i+'</a>';
                }
            }else if(json.result.pageNo<4){
                for(var i=1;i<6;i++){
                    data+='<a class="pageClick" pageNo='+i+'>'+i+'</a>';
                }
                data+='...<a class="pageClick" pageNo='+json.result.pageCount+'>'+json.result.pageCount+'</a>';
            }else{
                data+='<a class="pageClick" pageNo="1">1</a>...';
                data+='<a class="pageClick" pageNo='+(json.result.pageNo-2)+'>'+(json.result.pageNo-2)+'</a>';
                data+='<a class="pageClick" pageNo='+(json.result.pageNo-1)+'>'+(json.result.pageNo-1)+'</a>';
                data+='<a class="pageClick" pageNo='+json.result.pageNo+'>'+json.result.pageNo+'</a>';
                data+='<a class="pageClick" pageNo='+(json.result.pageNo+1)+'>'+(json.result.pageNo+1)+'</a>';
                data+='<a class="pageClick" pageNo='+(json.result.pageNo+2)+'>'+(json.result.pageNo+2)+'</a>';
                data+='...<a class="pageClick" pageNo='+json.result.pageCount+'>'+json.result.pageCount+'</a>';
            }
            if(json.result.pageNo == 1){
                $("#"+eleId).html('<table class="pager" pageNo="'+json.result.pageNo+'"><tbody><tr><td width="60%">'+data+'<span class="btn btn-small" id="pageNext">下一页</span><span class="btn btn-small" id="pageLast">尾页</span></td></tr></tbody></table>');
            }else if(json.result.pageCount == json.result.pageNo){
                $("#"+eleId).html('<table class="pager" pageNo="'+json.result.pageNo+'"><tbody><tr><td width="60%"><span class="btn btn-small" id="pageIndex">首页</span><span class="btn btn-small" id="pagePrev">上一页</span>'+data+'</td></tr></tbody></table>');
            }else{
                $("#"+eleId).html('<table class="pager" pageNo="'+json.result.pageNo+'"><tbody><tr><td width="60%"><span class="btn btn-small" id="pageIndex">首页</span><span class="btn btn-small" id="pagePrev">上一页</span>'+data+'<span class="btn btn-small" id="pageNext">下一页</span><span class="btn btn-small" id="pageLast">尾页</span></td></tr></tbody></table>');
            }
            $("a[pageNo="+json.result.pageNo+"]").addClass("laypage_curr").removeClass("pageClick");
            $("#" + eleId).off().on('click', '#pageIndex', function(event) {
                fn(1);
            });
            $("#" + eleId).on('click', '#pageLast', function(event) {
                fn(json.result.pageCount);
            });
            $("#" + eleId).on('click', '#pagePrev', function(event) {
                fn(parseInt(json.result.pageNo) - 1);
            });
            $("#" + eleId).on('click', '#pageNext', function(event) {
                fn(parseInt(json.result.pageNo) + 1);
            });
            $("#" + eleId).on('click', '.pageClick', function(event) {
                fn(parseInt($(this).attr('pageno')));
            });
        }else{
            $("#" + eleId).html('');
        }
    },
    /*
    *对选中的列表进行操作
    *msg.flag : true弹层提示,默认为false，无提示
    *msg.name : 操作名称，不需要弹层可不传
    *msg.sub : 无data也可上传，针对url带参上传方式，默认false
    *msg.url : 操作对应的接口
    *msg.method : 不传入默认为get
    *msg.data : 操作需要传递给接口的参数,不写默认为空
    *msg.fn : 刷新列表的方法
    *msg.pageNo: 刷新跳转到的页码(默认刷新到操作前页码)
    */
    operation : function(msg){
        msg.method = msg.method || "GET";
        msg.flag = msg.flag || false;
        msg.name = msg.name || '';
        msg.data = msg.data || '';
        msg.sub = msg.sub || false;
        if(!msg.pageNo) msg.pageNo = ($('.laypage_curr')) ? $('.laypage_curr').attr('pageno') : '1';
        if(msg.flag){
            if (msg.data || msg.sub){
                layer.confirm('确定要'+msg.name+'吗？',{
                time: 0
                ,btn: ['确定','取消']
                ,yes: function(index){
                    if(msg.name.indexOf('删除') >= 0){
                        if($('.checkbox').length == 2 && msg.pageNo > 1){
                            msg.pageNo = msg.pageNo - 1;
                        }
                    };
                    layer.close(index);
                    mccmsa.ajax({
                        url: msg.url,
                        method: msg.method,
                        data: msg.data,
                        success: function(){
                            if($('input.checkbox')[0]) $('input.checkbox')[0].checked = false;
                            msg.fn(msg.pageNo);
                        }
                    });
                 }
                });
            }else{
                layer.open({
                    type: 1, //page层
                    area: ['220px', '140px'],
                    title: '提示',
                    btn:"ok",
                    shade: 0.5, //遮罩透明度
                    moveType: 1, //拖拽风格，0是默认，1是传统拖动
                    shift: 0, //0-6的动画形式，-1不开启
                    content: '<div style="padding:10px 22px;">请先选择需要'+msg.name+'的用户</div>'
                });
            }
        }else{
            mccmsa.ajax({
                url: msg.url,
                method: msg.method,
                data: msg.data,
                success: function(){
                    $('input.checkbox')[0].checked = false;
                    msg.fn(msg.pageNo)
                }
            });
        }
    },
    /*
    *为列表绑定全选事件
    *input的class均为checkbox
    */
    checkAll : function(){
        $(document).on('click', 'input.checkbox',function(event) {
            var flag = true;
            var checkall = $('input.checkbox')[0];
            var that = $(this)[0];
            if(that == checkall){
                flag = that.checked;
                $('input.checkbox').each(function(index, el) {
                    $(this)[0].checked = flag;
                })
            }else{
                $('input.checkbox').each(function(index, el) {
                    if($(this)[0] != checkall) flag =($(this)[0].checked == false) ? false : flag;
                })
                checkall.checked = flag
            }
        });
    },
    /*
    * 作用：优化时间段选择（根据起始时间限制结束框最小时间，根据结束时间限制起始框最大时间）
    * 起始id：startTime，结束id：endTime
    */
    endtime : function(date, a){
        if(a){
            $('#endTime').off().on('click', function(){
                laydate({
                    choose : function(dates){
                        mccmsa.starttime(dates, '1')
                    },
                    min : date,
                    istime: true,
                    format: 'YYYY-MM-DD hh:mm:ss'
                });
            });
        }else{
            $('#endTime').off().on('click', function () {
                laydate({
                    choose: function (dates) {
                        mccmsa.starttime(dates)
                    },
                    min: date
                });
            });
        }
    },
    starttime : function(date, a){
        if(a){
            $('#startTime').off().on('click', function(){
                laydate({
                    choose : function(dates){
                        mccmsa.endtime(dates, '1')
                    },
                    max : date,
                    istime: true,
                    format: 'YYYY-MM-DD hh:mm:ss'
                });
            });
        }else{
            $('#startTime').off().on('click', function () {
                laydate({
                    choose: function (dates) {
                        mccmsa.endtime(dates)
                    },
                    max: date
                });
            });
        }
    },
    /*
    *【地区】选择
    *selectAll:获取所有列表data:{provinceId,cityId，areaId}
    *getProvinces：获取省
    *getProvinces：获取市 idF: 父级id
    *getProvinces：获取区 idF: 父级id
    */
    selectAll : function(date){
        date = (date) ? date : {provinceId : '',cityId : '',areaId : ''}
        if(date.provinceId == ''){
            mccmsa.getProvinces();
        }else{
            var allAddress = $.getCookie("cachedallAddressData");
            if(allAddress && allAddress.length > 0 && allAddress.id == date){
                var def = $.Deferred();

                var Address = JSON.parse(allAddress);
                mccmsa.getHtmlFromLocalTemplate({
                    templateId: "addressMsg",
                    container: $('#address'),
                    data: Address
                });

                def.resolve();
                return def;
            }else{
                mccmsa.ajax({
                    url: "/area/editAreaByConditions",
                    method:"GET",
                    data : date,
                    success: function(data){
                        if(data.status == 300){
                            return;
                        }
                        var allAddress = data.result.cities;
                        var allAddressForCache = {
                            "cities" : [],
                            "areas" : [],
                            "provinces" : []
                        };
                        if(data.result.cities){
                            for(var i = 0; i < data.result.cities.length; i++){
                                var citie = data.result.cities[i];
                                if(citie.cityID == date.cityId){
                                    allAddressForCache.cities.push({
                                        "id": citie.id,
                                        "cityID": citie.cityID,
                                        "city": citie.city,
                                        "fatherId": citie.fatherId,
                                        "checked": true
                                    }); 
                                }else{
                                    allAddressForCache.cities.push({
                                        "id": citie.id,
                                        "cityID": citie.cityID,
                                        "city": citie.city,
                                        "fatherId": citie.fatherId
                                    }); 
                                } 
                            };
                        }
                        if(data.result.areas){
                            for(var i = 0; i < data.result.areas.length; i++){
                                var area = data.result.areas[i];
                                if(area.areaId == date.areaId){
                                    allAddressForCache.areas.push({
                                        "id": area.id,
                                        "areaId": area.areaId,
                                        "area": area.area,
                                        "fatherId": area.fatherId,
                                        "checked": true
                                    });
                                }else{
                                    allAddressForCache.areas.push({
                                        "id": area.id,
                                        "areaId": area.areaId,
                                        "area": area.area,
                                        "fatherId": area.fatherId
                                    });
                                }
                            };
                        }
                        if(data.result.provinces){ 
                            for(var i = 0; i < data.result.provinces.length; i++){
                                var province = data.result.provinces[i];
                                if(province.provinceId == date.provinceId){
                                    allAddressForCache.provinces.push({
                                        "id": province.id,
                                        "provinceId": province.provinceId,
                                        "province": province.province,
                                        "checked": true
                                    });  
                                }else{
                                    allAddressForCache.provinces.push({
                                        "id": province.id,
                                        "provinceId": province.provinceId,
                                        "province": province.province
                                    });
                                }
                            }
                        }
                        var cachedallAddressStr = JSON.stringify(allAddressForCache);
                        if(cachedallAddressStr.length <= 4000){  // Cookie大小
                            mccmsa.setCookie("cachedallAddressData", cachedallAddressStr, 10 * 60 * 1000);  // 10分钟后过期
                        };
                        mccmsa.getHtmlFromLocalTemplate({
                            templateId: "addressMsg",
                            container: $('#address'),
                            data: allAddressForCache
                        });
                    }
                })
            }
        }
    },
    getProvinces : function(){
        // var Provinces = $.getCookie("Provinces");
        mccmsa.ajax({
            url: "/area/getAllProvinces",
            method:"GET",
            success: function(data){
                mccmsa.getHtmlFromLocalTemplate({
                    templateId: "provinceMsg",
                    container: $('#province'),
                    data: data
                });//获取省
            }
        })
    },
    getCities : function(idF){
        // var Cities = $.getCookie("Cities");
        if(idF){
            mccmsa.ajax({
                url: "/area/getCitiesByCondition",
                method:"GET",
                data: {
                    provinceId : idF //父级id
                },
                success: function(data){
                    mccmsa.getHtmlFromLocalTemplate({
                        templateId: "cityMsg",
                        container: $('#city'),
                        data: data
                    });//刷新市
                    mccmsa.getHtmlFromLocalTemplate({
                        templateId: "areaMsg",
                        container: $('#area'),
                    });//格式化区
                }
            })
        }else{
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "cityMsg",
                container: $('#city')
            });//格式化市
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "areaMsg",
                container: $('#area'),
            });//格式化区
        }
    },
    getAreas : function(idF){
        // var Areas = $.getCookie("Areas");
        if (idF) {
            mccmsa.ajax({
                url: "/area/getAreasByCondition",
                method:"GET",
                data: {
                    cityId : idF //父级id
                },
                success: function(data){
                    mccmsa.getHtmlFromLocalTemplate({
                        templateId: "areaMsg",
                        container: $('#area'),
                        data: data
                    });//刷新区
                }
            })
        }else{
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "areaMsg",
                container: $('#area'),
            });//格式化区
        }
    },
    /*
    *本地缓存方法
    *setCookie() 存储value到key
    *getCookie() 拿回key的value
    *key 关键字
    *value 值
    *expires 到期时间
    */
    setCookie: function(key, value, expires){
        var exdate=new Date();
        exdate.setTime(exdate.getTime()+ expires);
        document.cookie= key + "=" + escape(value)+
        ((expires==null) ? "" : ";expires="+exdate.toGMTString())
    },

    getCookie: function(key){
        if (document.cookie.length>0){
            c_start=document.cookie.indexOf(key + "=");
            if (c_start!=-1){
                c_start=c_start + key.length+1;
                c_end=document.cookie.indexOf(";",c_start);
                if (c_end==-1) c_end=document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end))
            }
        }
        return ""
    },
    /*
    *图片上传&文件上传
    *iptid 文件上传input的id <input type="file" id="?" name="file" />
    *容器内第一个元素为预览图,预览图必须有容器包裹
    *srcid 提交上传文件地址的input的id
    */
    uploadPhoto: function(iptid,srcid){
        var iptid = iptid;
        var httpUrl = '/notvsys';
        var iptEle = $("#" + iptid);
        var srcEle = $("#" + srcid);
        var val = $("#" + iptid).val();
        var reg = new RegExp('\.gif$|\.png$|\.jpg$|\.jpeg$|\.bmp$/i');
        if(document.getElementById(iptid).files[0].size > 1572864){
            layer.msg('不能上传超过1.5M的图片');
            return;
        }
        if(!reg.test(val.toLowerCase())){
            layer.msg('请确保上传文件为图片');
            return;
        }else{
            mccmsa.setImagePreview(iptid);
            if(iptEle.parent().find("img").length==2){
                iptEle.parents().show();
            }else{
                iptEle.after("<img class='loadImg' src='img/loadFile.gif'>")
            }
            $.ajaxFileUpload({
                beforeSend:function(){
                    imglock=true;
                },
                url: httpUrl + "/base/imageUpload",
                secureuri: false, //一般设置为false
                fileElementId: iptid, 
                dataType: 'json', //返回值类型 一般设置为json
                success: function (data, status){  //服务器成功响应处理函数
                    $(".loadImg").hide();
                    srcEle.val(data.result);
                    $("#" + iptid).change(function(){
                        mccmsa.uploadPhoto(iptid,srcid)
                    })
                    imglock=false;
                },
                error: function (data, status, e){//服务器响应失败处理函数
                    layer.msg(data.result);
                    $(".loadImg").hide();
                    iptEle.find('.update-img').attr('src','img/upload-img.png');
                    $("#" + iptid).change(function(){
                        mccmsa.uploadPhoto(iptid,srcid)
                    })
                     imglock=false;
                }
            })
        }
    },
    uploadFile: function(iptid,srcid){
        var httpUrl = '/notvsys';
        var iptEle = $("#" + iptid);
        var srcEle = $("#" + srcid);
        var val = iptEle.val();
        if(iptEle.parent().find("img").length == 1){
            iptEle.parents().find(".loadImg").show();
        }else{
            iptEle.before("<img class='loadImg' src='img/loadFile.gif'>")
        }
        $.ajaxFileUpload({
            url: httpUrl+"base/fileUpload", //用于文件上传的服务器端请求地址
            secureuri: false, //一般设置为false
            fileElementId: ['file'], //文件上传空间的id属性  <input type="file" id="file" name="file" />
            dataType: 'json', //返回值类型 一般设置为json
            success: function (data, status){  //服务器成功响应处理函数
                $(".loadImg").hide();
                srcEle.val(data.result);
                $("#" + iptid).change(function(){
                    mccmsa.uploadPhoto(iptid,srcid)
                })
            },
            error: function (data, status, e){//服务器响应失败处理函数
                layer.msg(data.result);
                $(".loadImg").hide();
                $("#" + iptid).change(function(){
                    mccmsa.uploadPhoto(iptid,srcid)
                })
            }
        })
    },
    /*
    *预览上传图片
    *inputId：input的id值,默认为：'doc';
    */
    setImagePreview: function(inputId){
        var docObj = document.getElementById(inputId) || document.getElementById('doc');  
        var fileName = docObj.value;
        var imgCotent = (docObj.previousSibling.nodeType == 1) ? docObj.previousSibling : docObj.previousSibling.previousSibling;
        var imgObjPreview = (imgCotent.firstChild.nodeType == 1) ? imgCotent.firstChild : imgCotent.firstChild.nextSibling;
        if (docObj.files && docObj.files[0]){  
            //火狐下，直接设img属性 
            //imgObjPreview.src = docObj.files[0].getAsDataURL(); 
            imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
        } else {  
            //IE下，使用滤镜  
            docObj.select();
            docObj.blur();  
            var imgSrc = document.selection.createRange().text;  
            var localImagId = imgCotent;  
            //设置初始大小  
            localImagId.style.width = docObj.currentStyle.width;  
            localImagId.style.height = docObj.currentStyle.Height;
            //图片异常的捕捉，防止用户修改后缀来伪造图片
            try {                  
                localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";  
                localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;  
            } catch (e) {  
                alert("您上传的图片格式不正确，请重新选择！");  
                return false; 
            }  
            imgObjPreview.style.display = 'none';  
            document.selection.empty();  
        }  
        return true; 
    },
    /*
    *上传图片容器id为ImgDiv加上数值，数值由0起
    *e： 第e个上传图片容器可用e为容器id中带的数值
    *h： 为true时设置图片容器为不可用，默认为false
    */
    ImgDivCtrl : function(e, h){
        var ele = $('#ImgDiv' + e),
        label = ele.find("label"),
        span = ele.find(".grey-fix"),
        file = ele.find("input[type='file']"),
        hidden = ele.find("input[type='hidden']"),
        a = ele.find('a'),
        h = h || false;
        if(h){
            label.addClass('disabled');
            span.removeClass('none');
            a.addClass('disabled');
            file.attr('disabled', 'true');
            hidden.attr('disabled', 'true');
            a.attr('disabled', 'true');
        }else{
            label.removeClass('disabled');
            span.addClass('none');
            a.removeClass('disabled');
            file.removeAttr('disabled');
            hidden.removeAttr('disabled');
            a.removeAttr('disabled');
        }
    },

    /*
     * 时间戳转格式为yyyy-MM-dd HH:mm:ss的字符串
     * */
    timeStampToString: function(timestamp) {
        var date = new Date(timestamp);

        return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    },

    /*
     *用于两个输入数值的input框验证，
     *min起始输入框,默认为id为min的input框
     *max起始输入框,默认为id为max的input框
     *ele错误提示元素类型，默认为span
     *main(t,s)t为输入完成的元素,s为错误提示元素的类名
     *value输入是否有误，布尔值
     */
    comparefunction: function(){
        this.min = document.getElementById('min');
        this.max = document.getElementById('max');
        this.value = false;
        this.ele = 'span';
        this.main = function(t,s){
            var o = (this.min == t) ? this.max : this.min,v = parseInt(t.value),i = t.getAttribute('data-min') || 0,a = t.getAttribute('data-max') || Infinity,p = document.createElement(this.ele),x = '',m = o.getAttribute('class') || '',c = t.getAttribute('class') || '',s = s || '';
            p.setAttribute('class', s);
            this.value = false;
            if(c.indexOf('wrong') >= 0){c = c.replace(' wrong','');this.removeAfter(t)};
            if(m.indexOf('wrong') >= 0){m = m.replace(' wrong','');o.setAttribute('class', m);this.removeAfter(o)};
            if (!isNaN(v)) {
                t.value = v;
                (t == this.min && v > 0) ? (this.max.setAttribute('data-min', v)) : (this.min.setAttribute('data-max', v));
                if(v < i || v > a){
                    x = document.createTextNode("请输入大于" + i +((a == Infinity)? '的数值' :"小于" + a + "的数值"));
                    c = c.concat(' wrong');
                }else{
                    this.value = true;
                }
            }else{
                x = document.createTextNode("请输入数值");
                c = c.concat(' wrong');
            }
            if(x){p.appendChild(x);this.insertAfter(p, t);t.setAttribute("class", c);this.value = false};
        };
        this.insertAfter = function(c, e){var p = e.parentNode,l = (p.lastChild.nodeType == 1) ? p.lastChild : p.lastChild.previousSibling,n = (e.nextSibling.nodeType == 1) ? e.nextSibling : e.nextSibling.nextSibling;(e == l) ? p.appendChild(c) : p.insertBefore(c, n)};
        this.removeAfter = function(e){var p = e.parentNode,n = (e.nextSibling.nodeType == 1) ? e.nextSibling : e.nextSibling.nextSibling;if(n)p.removeChild(n)};
        return this;
    },
    styleIcon : {
        '用户管理' : "basic-setting",
        '频道管理' : "ui-style",
        '互动管理' : "column-setting",
        '资源库' : "interaction-manager",
        '龙币管理' : "system-data",
        '系统管理' : "system-config"
    }
};

